//
//  ZHMWCaptionView.m
//  ZHPhotoBrowser
//
//  Created by Michael Waterfall on 30/12/2011.
//  Copyright (c) 2011 __MyCompanyName__. All rights reserved.
//

#import "ZHMWCommon.h"
#import "ZHMWCaptionView.h"
#import "ZHMWPhoto.h"

static const CGFloat labelPadding = 15;

// Private
@interface ZHMWCaptionView () {
    id <ZHMWPhoto> _photo;
    
    UILabel *_titleLab;
    UITextView *_textView;    
}
@end

@implementation ZHMWCaptionView

- (id)initWithPhoto:(id<ZHMWPhoto>)photo {
    self = [super initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, 44)]; // Random initial frame
    if (self) {
        _photo = photo;
        self.autoresizingMask = UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleTopMargin|UIViewAutoresizingFlexibleLeftMargin|UIViewAutoresizingFlexibleRightMargin;
        [self setupCaption];
    }
    return self;
}

- (CGSize)sizeThatFits:(CGSize)size {
    
    if (_textView.text.length < 1) {
        return CGSizeMake(size.width, 42);
    }
    CGRect textRect = [_textView.text boundingRectWithSize:CGSizeMake(size.width - labelPadding*2, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{ NSFontAttributeName : _textView.font } context:nil];
    
    CGFloat textHeight = MIN(textRect.size.height, 200);
    
    return CGSizeMake(size.width, textHeight + 42 + labelPadding);
}

- (void)setupCaption {
    
    self.backgroundColor = [UIColor colorWithWhite:0.1f alpha:0.5f];
    
    _titleLab = [[UILabel alloc] initWithFrame:CGRectMake(labelPadding, labelPadding, self.bounds.size.width-labelPadding*2, 16)];
    _titleLab.lineBreakMode = NSLineBreakByWordWrapping;
    _titleLab.textColor = [UIColor whiteColor];
    _titleLab.font = [UIFont systemFontOfSize:14];
    if ([_photo respondsToSelector:@selector(name)]) {
        _titleLab.text = [_photo name] ?: @"";
    }
    [self addSubview:_titleLab];
    
    _textView = [[UITextView alloc] initWithFrame:CGRectMake(labelPadding, 42, _titleLab.frame.size.width, self.bounds.size.height-42)];
    _textView.autoresizingMask = UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleHeight;
    _textView.textContainerInset = UIEdgeInsetsZero;
    _textView.contentInset = UIEdgeInsetsMake(0, -5, 0, 0);
    _textView.textAlignment = NSTextAlignmentLeft;
    _textView.backgroundColor = [UIColor clearColor];
    _textView.textColor = [UIColor whiteColor];
    _textView.font = [UIFont systemFontOfSize:13];
    
    _textView.editable = NO;
    if ([_photo respondsToSelector:@selector(caption)]) {
        _textView.text = [_photo caption] ?: @"";
    }
    [self addSubview:_textView];
}


@end
